/**
 * 
 */
package info.niwota.webapp.acl;

import info.niwota.commons.acl.AccessControl;
import info.niwota.commons.acl.AccessPermission;

import java.util.Arrays;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * Using shared preference as ACL store may not be the best option, but it
 * should serve well enough if data set is relatively small.
 * 
 * @author qiangli
 * 
 */
public class PermStore {
	private static final String PERM_STORE_PREF = "perm_store_pref";
	private SharedPreferences store;
	private static final String FIELD_SEP = "|";
	private static final String FIELD_SEP_REGEX = "\\|";

	public PermStore(Context ctx) {
		store = ctx.getSharedPreferences(PERM_STORE_PREF, Context.MODE_PRIVATE);
	}

	public void store(String label, String perm, String emails) {
		emails = (emails == null ? "" : emails);
		String access = (perm == null ? AccessControl.S_ACCESS_MASTER : perm
				.toString())
				+ FIELD_SEP + emails;
		Editor ed = store.edit();
		ed.putString(label, access);
		ed.commit();
	}

	/**
	 * @param label
	 * @return array of permission and emails or default values if not found
	 */
	public String[] getPerm(String label) {	
		String access = store.getString(label, null);
		return parsePerm(access);
	}
	
	/**
	 * Convenience method
	 * 
	 * @param ctx
	 * @param label
	 * @return array of permission and emails or default values if not found
	 */
	public static String[] getPerm(Context ctx, String label) {	
		SharedPreferences store = ctx.getSharedPreferences(PERM_STORE_PREF, Context.MODE_PRIVATE);
		String access = store.getString(label, null);
		return parsePerm(access);
	}

	public AccessPermission[] loadPerms() {
		Map<String, ?> all = store.getAll();
		int size = all.size();
		AccessPermission[] perms = new AccessPermission[size];
		int i = 0;
		for (Map.Entry<String, ?> e : all.entrySet()) {
			AccessPermission p = new AccessPermission();
			p.label = e.getKey();
			p.icon = null;
			p.desc = "";
			String[] pa = parsePerm(e.getValue().toString());
			p.perm = pa[0];
			p.emails = pa[1];
			//
			perms[i++] = p;
		}
		//
		Arrays.sort(perms);
		return perms;
	}

	private static String[] parsePerm(String access) {
		String[] pa = new String[] { AccessControl.S_ACCESS_MASTER, "" };
		if (access != null) {
			String[] sa = access.split(FIELD_SEP_REGEX, 2);
			pa[0] = sa[0];
			pa[1] = (sa.length > 1 ? sa[1] : "");
		}
		return pa;
	}
}
